package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.BookService;
import com.longkier.gx_library_springboot.entity.Book;
import com.longkier.gx_library_springboot.exception.CustomException;
import com.longkier.gx_library_springboot.utils.FileUploadUtils;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 图书控制器，处理图书的请求。
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/book")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class BookController {

    private static final Logger logger = LoggerFactory.getLogger(BookController.class);
    private final BookService bookService;

    /**
     * 获取图书封面图片
     *
     * @param fileName 文件名（图书编号）
     * @return 返回图片文件
     * @throws IOException 文件读取异常
     */
    @GetMapping("/image/{fileName:.+}")
    public ResponseEntity<byte[]> getStaticResource(@PathVariable String fileName) throws IOException {
        // 尝试读取请求的文件
        ResponseEntity<byte[]> response = FileUploadUtils.readFileAndSetHeaders(fileName);
        if (response != null) {
            return response;
        } else {
            // 如果文件不存在，返回默认图像
            return FileUploadUtils.readFileAndSetHeaders("null.jpg");
        }
    }

    /**
     * 处理新增图书请求。
     *
     * @param book 图书实体
     * @param file 图书封面文件
     * @return 新增结果
     */
    @PostMapping("/addBook")
    public Map<String, Object> addBook(@RequestPart("book") Book book, @RequestPart(value ="file",required = false) MultipartFile file) {
        try {
            if(bookService.addBook(book,file)){
                return RequestUtils.buildResponse("新增图书成功", 200);
            } else {
                return RequestUtils.buildResponse("新增图书失败", 500);
            }
        } catch (Exception e) {
            logger.error("新增图书失败: {}", e.getMessage());
            throw new CustomException(500, "新增图书时发生异常");
        }
    }

    /**
     * 根据图书 ID 批量删除图书。
     *
     * @param params 请求体，包含 bookId
     * @return 删除结果
     */
    @DeleteMapping("/batch/delete")
    public Map<String, Object> deleteBook(@RequestBody Map<String, Object> params) {
        try {
            List<Long> bookId = RequestUtils.processIds(params.get("bookId"));
            boolean success = bookService.batchDeleteUsers(bookId);
            if (success) {
                return RequestUtils.buildResponse("删除图书成功", 200);
            } else {
                throw new CustomException(404, "删除失败，图书不存在");
            }
        } catch (Exception e) {
            throw new CustomException(500, "删除图书时发生异常");
        }
    }

    @GetMapping("/{bookNumber}")
    public Map<String, Object> getByBookNumber(@PathVariable String bookNumber) {
        try {
            Optional<Book> book = bookService.getByBookNumber(bookNumber);
            if (book.isPresent()) {
                return RequestUtils.buildResponse(book, 200);
            } else {
                throw new CustomException(404, "图书不存在");
            }
        } catch (Exception e) {
            throw new CustomException(500, "查询图书时发生异常");
        }
    }

    /**
     * 分页查询所有图书。
     *
     * @param request 请求体，包含 page、size、bookNumber、bookName、bookAuthor、bookArea、bookType、bookStatus
     * @return 用户列表
     */
    @PostMapping("/all")
    public Map<String, Object> getBooks(@RequestBody Map<String, Object> request) {
        int page = (int) request.getOrDefault("page", 0);
        int size = (int) request.getOrDefault("size", 10);
        String bookNumber = RequestUtils.getStringFromRequest(request,"bookNumber");
        String bookName = (String) request.get("bookName");
        String bookAuthor = (String) request.get("bookAuthor");
        String bookArea = (String) request.get("bookArea");
        String bookType = (String) request.get("bookType");
        String bookStatus = (String) request.get("bookStatus");
        try {
            return RequestUtils.buildResponse(bookService.getBooksServices(page, size,
                    bookNumber, bookName, bookAuthor,bookArea,bookType,bookStatus),200);
        } catch (Exception e) {
            throw new CustomException(500, "查询图书列表时发生异常");
        }
    }

    /**
     * 更新图书信息。
     *
     * @param book 图书实体
     * @return 更新结果
     */
    @PutMapping("/update")
    public Map<String, Object> updateBook(@RequestPart("book") Book book,  @RequestPart(value ="file",required = false) MultipartFile file) {
        try {
            boolean success = bookService.updateBook(book,file);
            if (success) {
                return RequestUtils.buildResponse("更新图书成功", 200);
            } else {
                throw new CustomException(404, "更新失败，图书不存在");
            }
        } catch (Exception e) {
            //logger.error("更新图书时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "更新图书时发生异常");
        }
    }

    /**
     * 批量设置图书状态
     *
     * @param request 请求体，包含 bookIds 和 status
     * @return 更新状态结果
     */
    @PutMapping("/batch/update/status")
    public Map<String, Object> batchUpdateStatus(@RequestBody Map<String, Object> request) {
        try {
            List<Long> bookIds = RequestUtils.processIds(request.get("bookIds"));
            String status = (String) request.get("status");

            boolean success = bookService.batchUpdateStatus(bookIds, status);
            if (success) {
                return RequestUtils.buildResponse("更新状态成功",200);
            } else {
                throw new CustomException(500, "部分图书更新状态失败");
            }
        } catch (IllegalArgumentException e) {
            throw new CustomException(400, e.getMessage());
        } catch (Exception e) {
            throw new CustomException(500, "更新图书状态时发生异常");
        }
    }

}
